package zzcltw.com.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import net.sf.json.JSONObject;
import zzcltw.com.object.SysMenu;
import zzcltw.com.service.ISystemService;
import zzcltw.com.service.IUserService;
import zzcltw.com.util.Constants.FTP_CONFIG;
import zzcltw.com.util.DateUtil;
import zzcltw.com.util.FtpClient;
import zzcltw.com.util.MySFtp;
import zzcltw.com.util.PropertiesUtil;


@RestController
public class SysController {
	@Autowired
	private Environment env;
	@Autowired
    private ISystemService systemService;
	/**
	 * 
	 */
	private static final long serialVersionUID = -3983037068878331518L;

	//@RequestMapping("/hello")
	@RequestMapping("/getUserById")
    public String index() {
        return "测3333v嘎嘎嘎试spring";
    }
	@Autowired
    private IUserService userService;

    /*@ResponseBody
    @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
    public int addUser(User user){
        return userService.addUser(user);
    }
    @ResponseBody
    @RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"})
    public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){

        return userService.findAllUser(pageNum,pageSize);
    }
    @RequestMapping(value="/getUsers",method = RequestMethod.GET)
    public List<User> getUsers() {
        return userService.getAll();
    }*/
    /*@RequestMapping(value="/getListUsers",method = RequestMethod.GET)
    public void getList(String userName,String aaaa,String bbbb) {
    	//Map<String,Object> param=CommonAction.convert(req);
    	//InputObject n = (InputObject) ServletActionContext.getContext().get(ControlConstants.INPUTOBJECT);
    	Map<String,String> map = new HashMap<>();
    	map.put("userName", userName);
    	//map.put("userName", aaaa);
    	//map.put("userName", bbbb);
    	userService.test(map);
    	//userService.getAll();
    	//System.err.println("**************完成***********8");
       // return userService.test(map);
    }*/
    @RequestMapping(value="/uploadPicFile", method=RequestMethod.POST)  
    @ResponseBody
    public  Map<String,Object> uploadPicFile(@RequestParam("uploadfile") MultipartFile file){//@RequestParam("uploadfile") MultipartFile file
    	FtpClient ftp = new FtpClient();
    	Map<String,Object> rtnMap = new HashMap<>();
		try {
			int code = (int) ((Math.random() * 9 + 1) * 100000);
			String fileName = file.getOriginalFilename();// DateUtil.date2String(new Date(),DateUtil.DATE_PATTERN.YYYYMMDDHHMMSS)+ code+".jpg";
			if(fileName != null ){//&& fileContent != null
				
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String dateStr = df.format(new Date());
			String imgStr=file.getOriginalFilename().toLowerCase();//fileName.toLowerCase();
			//String randomNum=NCode.createRandom(true, 4);
            if(imgStr.endsWith("jpg") || imgStr.endsWith("gif") || imgStr.endsWith("jpeg") || imgStr.endsWith("bmp") || imgStr.endsWith("png")){
            	//图片名称改为只要字符串 不要上传文件的名称
            	fileName = new StringBuilder().append(dateStr).append(code ).append( fileName.substring(fileName.lastIndexOf("."))).toString();
            	
            	InputStream is = file.getInputStream();
            	// ftp服务地址
            	String hostIp = "172.17.14.58";//PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_IP);
            	//String hostIp = "47.93.36.223";
            	// ftp端口
            	int port = 21;//PropertiesUtil.getInt(FTP_CONFIG.FTP_HOST_PORT);
            	// ftp用户账号
            	String userName = "ftpuseradm";//PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_USERNAME);
            	// ftp用户密码
            	String userPwd = "1qaz!QAZ";//PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_USERPD);
            	
            	String remotePath = "/home/ftpuser/ftp/pic/";//PropertiesUtil.getString(FTP_CONFIG.FTP_UPLOAD_PATH_PIC);

            	ftp.ftp1(hostIp, port, userName, userPwd);
            	ftp.storeFile(remotePath+fileName, is);
            	//FTP访问地址            	
            	rtnMap.put("", "0");//.setReturnCode("0");
            	Map<String,String> map = new HashMap<>();
            	map.put("fileName", fileName);
            	String ftpUrlApp = "/home/ftpuser/ftp/pic/";//PropertiesUtil.getString(Constants.FTP_CONFIG.FTP_UPLOAD_PATH_PIC_NGINX);
            	map.put("picUrl",ftpUrlApp +"/"+ fileName);
            	rtnMap.put("picUrl", ftpUrlApp + fileName);
            	rtnMap.put("fileName", fileName);
            	rtnMap.put("rtnCode", "00");
            }else{
            	//object.setReturnMessage("系统异常！");
            }
            	
			}
		} catch (Exception exception) {
			//System.err.print("*******上传失败*********");
		} finally {
			//sf.disconnect(sftp);
		}
    	return rtnMap;
    }  
    /**
     * 新增菜单
     * @param sysMenu
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/saveUiInfo",method = RequestMethod.POST)
    public Map<String,Object> saveUiInfo(SysMenu sysMenu) throws Exception {
    	sysMenu.setCrtUserId("123456789");
    	sysMenu.setUiValidFlag("1");
        return systemService.saveMenuInfo(sysMenu);
    }
    @RequestMapping("/upLoad")
    public void uploadPicImg(HttpServletRequest request, HttpServletResponse response){
    	//System.err.print("*******图片开始********");
    	Map<String,Object> rtnMap = new HashMap<>();
    	FtpClient ftp = new FtpClient();
    	try {       
           // PrintWriter out = response.getWriter();
            //定义允许上传的文件扩展名
            HashMap<String, String> extMap = new HashMap<String, String>();
            extMap.put("image", "gif,jpg,jpeg,png,bmp");
            extMap.put("flash", "swf,flv");
            extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

            //最大文件大小
            long maxSize = 1000000;
            response.setContentType("text/html; charset=UTF-8");
            //创建一个DiskFileItemFactory工厂
            FileItemFactory factory = new DiskFileItemFactory();
            //创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置编码
            upload.setHeaderEncoding("UTF-8");
            //判断提交上来的是list数据
            List items = upload.parseRequest(request);
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Iterator item = multipartRequest.getFileNames();
//          Iterator itr = items.iterator();
            String remotePath = "/home/ftpuser/ftp/pic/";
            while (item.hasNext()) {
                String fileName = (String) item.next();

                MultipartFile file = multipartRequest.getFile(fileName);

               // 检查扩展名
                String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                    try {
                    String hostIp = "172.17.14.58";//PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_IP);
                	// ftp端口
                	int port = 21;//PropertiesUtil.getInt(FTP_CONFIG.FTP_HOST_PORT);
                	// ftp用户账号
                	String userName = "ftpuseradm";//PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_USERNAME);
                	// ftp用户密码
                	String userPwd = "1qaz!QAZ";//PropertiesUtil.getString(FTP_CONFIG.FTP_HOST_USERPD);
                	
                	ftp.ftp1(hostIp, port, userName, userPwd);
                	ftp.storeFile(remotePath+newFileName, file.getInputStream());
                    } catch (Exception e) {
                    }
                  // rtnMap.put("error", 0);
                   //rtnMap.put("picUrl", "47.93.36.223:80"+remotePath + newFileName);
                   response.setContentType("text/json;charset=UTF-8");  
                   response.setHeader("Cache-Control", "no-cache"); 
                   response.reset();
                   //PrintWriter pw = response.getWriter();  
                   //resp.reset();
                   Map<String,String> map = new HashMap<>();
                   map.put("picUrl", "47.93.36.223:80"+remotePath + newFileName);
                   rtnMap.put("bean", map);
                   //Map<String,Object> map1 = new HashMap<>();
           		//map1.put("beans", list);
           		//map1.put("bean", bean);
                   rtnMap.put("busiCode", "");
           		rtnMap.put("returnCode", "0");
           		rtnMap.put("returnMessage", "");
           		rtnMap.put("object", "");
           		rtnMap.put("busiCode", ""); 
                   JSONObject jsonObject = new JSONObject();//JSONObject.fromObject(rtnMap); 
                   jsonObject.put("url", "47.93.36.223:80"+remotePath + newFileName);
                   jsonObject.put("error", "0");
                   String str = jsonObject.toString();
                   //str = str.replace("\"", "\\\"");
                   response.getOutputStream().println(str); 
                   response.getOutputStream().flush(); 
                   response.getOutputStream().close();
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
		//return rtnMap;
	}
   public static void main(String[]arg){
	   Map<String,Object> rtnMap = new HashMap<>();
	   rtnMap.put("error", 0);
       rtnMap.put("picUrl", "47.93.36.223:80/home/ftpuser/ftp/20180916191437_624.png");
       Map<String,String> map = new HashMap<>();
       map.put("picUrl", "47.93.36.223:80/home/ftpuser/ftp/20180916191437_624.png");
       rtnMap.put("bean", map);
       JSONObject jsonObject = JSONObject.fromObject(rtnMap); 
       String str = jsonObject.toString();
      // System.err.println("原：****"+str);
      // System.err.println("改变后**"+str.replace("\"", "\\\""));
   }
    /**
     * 新增菜单
     * @param queryUiList
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryUiList")
    public Map<String,Object> queryUiList(String limit ,String start) throws Exception {
    	Map<String,String> map = new HashMap<>();
    	map.put("start", start);
    	map.put("limit", limit);
        return systemService.queryMenuList(map);
    }
    /**
     * 首页菜单列表
     * @param queryMenuLeftTop
     * @return
     * @throws Exception
     */
    @RequestMapping("/homePageMenu")
    public Map<String,Object> queryMenuLeftTop() throws Exception {
    	Map<String,String> map = new HashMap<>();    	
        return systemService.queryMenuLeftTop(map);
    }
    /**
     * 编辑菜单
     * @param sysMenu
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/editUiInfo",method = RequestMethod.POST)
    public Map<String,Object> editUiInfo(SysMenu sysMenu) throws Exception {
        return systemService.updateMenuInfo(sysMenu);
    }
    /**
     * 删除菜单
     * @param sysMenu
     * @return
     * @throws Exception
     */
    @RequestMapping("/delUiInfo")
    public Map<String,Object> delUiInfo(SysMenu sysMenu) throws Exception {
        return systemService.delMenuInfo(sysMenu);
    }
}
